
package cnhy.salary.controller;

import cn.hutool.core.date.DateUtil;
import cnhy.salary.domain.Employee;
import cnhy.salary.domain.LeaveRecord;
import cnhy.salary.domain.dto.EmployeeDto;
import cnhy.salary.service.DepartmentSvc;
import cnhy.salary.service.EmployeeSvc;
import com.easy.query.api4j.sql.SQLWherePredicate;
import com.easy.query.core.expression.lambda.SQLExpression1;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import cnhy.salary.domain.PostTransfer;
//import cnhy.salary.service.PostTransferService;
import ling.common.*;
import ling.common.domain.*;

 /** 调换岗 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-5-26
 */
@Api(tags = "调换岗 功能接口")
@RestController
@RequestMapping("/salary/PostTransfer")
public class PostTransferController extends EQueryController<PostTransfer>{


    @Resource
     PowerService powerService;
     @Resource
    DepartmentSvc departmentSvc;
    @ApiOperation("详情")
    @PreAuthorize("@ps.any(@pay.postTransfer.query)")
    @GetMapping(value = "/{id}")
    public Result<PostTransfer> getInfo(@PathVariable("id") Long id)
    {
       return super.getInfo(id);
    }
    
    @ApiOperation("分页列表,返回能本部及下级的，all=1和adm管理员看所有")
    @PreAuthorize("@ps.any(@pay.postTransfer.list)")
    @GetMapping("list")
    public ResultRows<PostTransfer> list(PostTransfer dto,Integer all, PageDomain pageRequest) {
//        if (Objects.equals(dto.getNewDept(), -100L))
//            dto.setNewDept(getDeptId());

        if (Objects.equals(all, 1) || powerService.hasRole("adm") || SecurityUtils.isAdmin(getUserId())) {
            return queryPage(dto, pageRequest);
        }
        // 主任审批时查看范围处理
        var ids = departmentSvc.childrenIds(getDeptId());
        ids.add(getDeptId());
        SQLExpression1<SQLWherePredicate<PostTransfer>> where = p -> p.in(PostTransfer::getNewDept, ids);
        return queryPage(dto, pageRequest, where);
    }

    
    @ApiOperation("新增")
    @PreAuthorize("@ps.any(@pay.postTransfer.add)")
    @Log(title = "调换岗", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody PostTransfer entity) {
        //记录旧，设置新
        var emplDto = queryHelper.queryable(EmployeeDto.class).where(p -> p.eq(EmployeeDto::getUserId, entity.getUserId())).firstOrNull();
        entity.setBegin(new Date());
        if (entity.getType() == 0)
            entity.setEnd(DateUtil.endOfDay(entity.getBegin()));
        entity.setOldDept(emplDto.getDeptId());
        entity.setOldDeptName(emplDto.getDeptName());
        entity.setOldLv2(emplDto.getPost());
        entity.setOldLv2Name(emplDto.getPostName());
        entity.setOldLv3(emplDto.getLineId());
        entity.setOldLv3Name(emplDto.getLineName());
        if (entity.skipApprovalBy100()) {
            postSetBy(entity);
            return super.add(entity);
        } else
            entity.approval(1, null, null);
        return super.add(entity);
    }
    
    @ApiOperation("删除")
    @PreAuthorize("@ps.any(@pay.postTransfer.remove)")
    @Log(title = "调换岗", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable("ids") Long[] ids){
        return super.remove(Arrays.stream(ids).toArray());
    }
    
    @ApiOperation("编辑")
    @PreAuthorize("@ps.any(@pay.postTransfer.edit)")
    @Log(title = "调换岗", businessType = BusinessType.UPDATE)
    @PutMapping
    public  Result edit(@Validated @RequestBody PostTransfer entity){
        return super.edit(entity);
    }

     @ApiOperation(value = "岗位确认",notes = "需要字段：id,status审批结果100通过,approvalRecord审批备注")
     @PreAuthorize("@ps.any(@pay.postTransfer.edit)")
     @Log(title = "调换岗", businessType = BusinessType.UPDATE)
     @PostMapping("/approval")
     @Transactional
     public  Result approval(@Validated @RequestBody PostTransfer entity) {
         var old = queryHelper.entityQuery(PostTransfer.class).whereById(entity.getId()).firstOrNull();
         if (entity.getStatus() == 100 && DateUtil.endOfDay(old.getBegin()).isBefore(DateUtil.beginOfDay(new Date()))) {
             return Result.bad("已过期,审批需当天确认，请驳回后重新发起");
         }
         old.approval(entity.getStatus() == 100, entity.getApprovalRecord(), null);

         queryHelper.queryClient().updatable(old).executeRows();
         if (entity.status != 100)
             return Result.ok();
         //通过后设置员工岗位
         return postSetBy(old);
     }

     @Resource
EmployeeSvc employeeSvc;
     private Result postSetBy(PostTransfer old) {
         var empl = queryHelper.entityQuery(Employee.class).where(e -> e.userId().eq(old.getUserId())).firstOrNull();
         if (old.getType() == 0) {
             empl.setTempPost(old.getNewLv2());
             empl.setTempPostName(old.getNewLv2Name());
             empl.setTempDept(old.getNewDept());
             empl.setTempBegin(old.getBegin());
         } else if (old.getType() == 1) {
             empl.setPost(old.getNewLv2());
             empl.setPostName(old.getNewLv2Name());
             empl.setDeptId(old.getNewDept());
         }
         return employeeSvc.editEmployee(empl);
         //queryHelper.query().updatable(empl).executeRows();
     }


     @ApiOperation("导出")
    @PreAuthorize("@ps.any(@pay.postTransfer.export)")
    @Log(title = "调换岗", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(PostTransfer entity, PageDomain pageRequest,HttpServletResponse response)
    {
        super.export(entity,pageRequest,null,response);
    }
}